package com.yu.newsSys.controller;

import com.yu.newsSys.constants.SessionConstants;
import com.yu.newsSys.service.AdminService;
import com.yu.newsSys.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @RequestMapping("/checkUser")
    @ResponseBody
    public Result checkUser(String username) {
        return adminService.checkUserName(username);
    }

    @RequestMapping("/zhuce")
    @ResponseBody
    public Result zhuce(String username, String password) {
        return adminService.save(username,password);
    }

    @RequestMapping("/login")
    @ResponseBody
    public Result login(String username, String password,HttpServletRequest request) {

        Result result = adminService.checkUser(username, password);
        if (result.getCode() == 200) {
            // 将用户信息保存到session中
            request.getSession().setAttribute(SessionConstants.USER_SESSION,username);
        }
        return result;
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest req) {
        // 正常退出时将用户信息从session中清除
        HttpSession session = req.getSession();
        session.removeAttribute(SessionConstants.USER_SESSION);
        session.invalidate();
        return Result.OK();
    }
}
